package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.resp.task.EggTaskFinishCase;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.mapper.TbClubTaskParameterMapper;
import com.quanyan.club.mapper.TbClubTaskSummaryLogMapper;
import com.quanyan.club.mapper.TbOperateLotteryPrizeItemsMapper;
import com.quanyan.club.service.ClubTaskEggService;
import com.quanyan.club.service.CppService;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 俱乐部任务统计定时器
 * 每周日23:59:00分才执行
 */
@Component
public class ClubTaskSummaryJob implements JobRunner{

    private static Logger logger = Logger.getLogger(ClubTaskSummaryJob.class);
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubTaskSummaryLogMapper clubTaskSummaryLogMapper;
    @Autowired
    private CppService cppService;
    @Autowired
    private ClubTaskEggService clubTaskEggService;
    @Autowired
    private TbClubTaskParameterMapper clubTaskParameterMapper;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        logger.warn("执行俱乐部积分统计任务， 当前时间：" + JSON.toJSONString(new Date()));
        Job job = jobContext.getJob();
        if (job == null) {
            return new Result(Action.EXECUTE_EXCEPTION, "任务不存在");
        }

        updateLotteryDay();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月 ");
        String weekStr = sdf.format(new Date()) + "第" + DateUtils.getWeekOfMonth(new Date()) + "周";
        logger.warn("统计俱乐部鸟蛋任务，" + weekStr);

        List<EggTaskFinishCase> finishCaseList =  new ArrayList<>();
                //clubTaskEggService.queryFinishEggTaskClubs();
        if (finishCaseList == null || finishCaseList.size() == 0){
            logger.warn(weekStr + "，没有俱乐部结算活动");
            return new Result(Action.EXECUTE_SUCCESS);
        }

        for (EggTaskFinishCase taskFinishCase : finishCaseList){
            logger.warn("统计：" + JSON.toJSONString(taskFinishCase));

            clubTaskEggService.recordClubWeekTaskSummary(taskFinishCase, true);

            //完成了任务但没有领取，发送通知给用户
            final String msg = buildFinishTaskLevelMsg(taskFinishCase);
            if (!StringUtil.isBlankOrNull(msg)){
                final TbClub tbClub = clubMapper.selectByPrimaryKey(taskFinishCase.getClubId());
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        cppService.pushClubCommonMsg(tbClub.getLogoUrl(), msg, Arrays.asList(tbClub.getUid()));
                    }
                }, 1000 * 60 * 60 * 8);     //8小时后执行 * 60 * 60 * 8
            }
        }

        return new Result(Action.EXECUTE_SUCCESS);
    }

    /**
     * 记录俱乐部一周的鸟蛋任务完成情况
     */
//    private void recordClubWeekTaskSummary(EggTaskFinishCase taskFinishCase){
//        TbClubTaskSummaryLogExample example = new TbClubTaskSummaryLogExample();
//        example.createCriteria()
//                .andClubIdEqualTo(taskFinishCase.getClubId())
//                .andWeekEqualTo(taskFinishCase.getWeek());
//        if (clubTaskSummaryLogMapper.countByExample(example) > 0){
//            return;
//        }       //本周已经统计了不再统计
//
//        TbClubTaskSummaryLog log = new TbClubTaskSummaryLog();
//        log.setWeek(taskFinishCase.getWeek());
//        log.setClubId(taskFinishCase.getClubId());
//        log.setTaskId(taskFinishCase.getTaskParamterId());
//        log.setIsFinishTask(taskFinishCase.isCanbeget());
//        boolean isGotAwards = taskFinishCase.isAlreadyget();
//        log.setIsGotAwards(isGotAwards);
//
//        int f_activity_count = taskFinishCase.getWeekActivityFinishCount();
//        int f_signup_count = taskFinishCase.getWeekSignupFinishCount();
//        log.setActivityCount(f_activity_count);
//        log.setSignupCount(f_signup_count);
//
//        if (isGotAwards){
//            log.setClubGetEggs(taskFinishCase.getEggForClub());
//            log.setMemGetEggs(taskFinishCase.getEggForMem());
//            log.setCoefficient(getCoefficient(taskFinishCase));
//            log.setGetAwardsTime(taskFinishCase.getGetAwardTime());
//        }
//        log.setCreateTime(new Date());
//        log.setUpdateTime(new Date());
//        clubTaskSummaryLogMapper.insertSelective(log);
//    }


    /**
     * 计算任务完成系数
     */
//    private double getCoefficient(EggTaskFinishCase taskFinishCase){
//        int f_activity_count = taskFinishCase.getWeekActivityFinishCount();     //实际完成
//        int f_signup_count = taskFinishCase.getWeekSignupFinishCount();
//        int t_activity_count = taskFinishCase.getWeekActivityTargetCount();     //实际
//        int t_signup_count = taskFinishCase.getWeekSignupTargetCount();
//
//        double coefficient = 0d;
//        if (f_activity_count > t_activity_count && f_signup_count > t_signup_count){      //  	超额完成公式：{实际活动数/任务要求活动数+(（实际完成人次数-任务要求人次数)/任务要求人次数）* 0.7 + 1}/2；
//            coefficient = (f_activity_count/(t_activity_count*1.0) + (((f_signup_count-t_signup_count)/(t_signup_count*1.0))/(t_signup_count*1.0))*0.7 +1)/2.0;
//        }else {             //  	未完成任务公式：（实际完成活动数/任务要求活动数+实际完成人次数/任务要求人次数）/2
//            coefficient = (f_activity_count/t_activity_count + f_signup_count/t_signup_count)/2.0;
//        }
//
//        return coefficient;
//    }

    /**
     * 获取完成的任务级别，并组装消息
     */
    private String buildFinishTaskLevelMsg(EggTaskFinishCase taskFinishCase){

        if (taskFinishCase.isAlreadyget()){     //已经领取了，不再发消息
            return null;
        }

        int clubId = taskFinishCase.getClubId();
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub.getIsDelete() == 1 || tbClub.getStatus() != 0){
            return null;
        }
        int clubType = tbClub.getClubType();

        TbClubTaskParameterExample example = new TbClubTaskParameterExample();
        example.createCriteria()
                .andClubTypeEqualTo(clubType)
                .andTaskIdEqualTo(taskFinishCase.getTaskId());
        example.setOrderByClause(" activity_target_count+signup_target_count desc");
        List<TbClubTaskParameter> parameterList = clubTaskParameterMapper.selectByExample(example);
        if (parameterList == null || parameterList.size() == 0){
            return null;
        }
        int finishLevel = -1;
        for (int i = 0; i < parameterList.size(); i++){
            if (parameterList.get(i).getActivityTargetCount() <= taskFinishCase.getWeekActivityFinishCount()
                    && parameterList.get(i).getSignupTargetCount() <= taskFinishCase.getWeekSignupFinishCount()){
                finishLevel = i;
                break;
            }
        }

        String level = "一";
        if (finishLevel == -1){
            return null;
        }
        finishLevel = parameterList.size() - finishLevel;
        if (finishLevel == 2){
            level = "二";
        }
        if (finishLevel == 3){
            level = "三";
        }
        int psize = parameterList.size();
        String msg = "";

        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd");
        String taskName = "(" + "周任务" + sdf.format(DateUtils.getMondayOfWeek(taskFinishCase.getWeekDate(), 0))
                + " - " + sdf.format(DateUtils.getSundayOfWeek(taskFinishCase.getWeekDate(), 0)) + ")";

//        if (psize == 1){
//            msg += "恭喜您！你的俱乐部\""+tbClub.getClubName()+"\"完成了" + taskName;
//        }else {
//            msg += "恭喜您！你的俱乐部\""+tbClub.getClubName()+"\"完成了" + level +"级" + taskName;
//        }
        if (finishLevel == psize){
            msg += "恭喜您！你的俱乐部\""+tbClub.getClubName()+"\"完成了" + level +"级" + taskName;
            msg += "请等待下周一即可领取鸟蛋奖励！";
        }
//        else {
//            msg += "请去俱乐部主页领取鸟蛋奖励！";
//        }

        return  msg;
    }

    @Autowired
    private TbOperateLotteryPrizeItemsMapper lotteryPrizeItemsMapper;

    private void updateLotteryDay(){
        TbOperateLotteryPrizeItemsExample example = new TbOperateLotteryPrizeItemsExample();
        example.createCriteria().andTypeEqualTo(0);
        List<TbOperateLotteryPrizeItems> prizeItemses = lotteryPrizeItemsMapper.selectByExample(example);
        if (prizeItemses != null && prizeItemses.size() != 0){
            for (TbOperateLotteryPrizeItems prizeItems : prizeItemses){
                prizeItems.setNumOfDayGrantLeftover(prizeItems.getNumOfDayGrant());
                lotteryPrizeItemsMapper.updateByPrimaryKeySelective(prizeItems);
            }
        }
    }
}
